/*** Class Name: IfulfillQueryEmailHandler
  * Author: Accenture * Date: 13-Sep-2011 
  * Requirement/Project Name: iFulfill 
  * Requirement Description: Handles Query submission and response to sales reps
**/
public class ifulfillSubmitToSalesRepController
{    
    private Queries__c qry = new Queries__c();

    /*
     * Constructor 
     * 
     **/
    public ifulfillSubmitToSalesRepController(ApexPages.StandardController controller) 
    {         qry = (Queries__c)controller.getRecord(); 
    }  
    
    /*
     *  Action associated with submit to sales rep button on query page layout.
     *
     **/      
    public pagereference SubmitToSalesRep()
    {                 
        ID OORSalesId = RecordTypeHelper.GetRecordTypeID('Queries__c', 'OOR Sales Rep');   
        qry.Time_Queried__c = qry.Time_Queried__c + 1;
        qry.Last_Queried_on__c = System.NOW();
        qry.recordtypeid = OORSalesId;        
        qry.Submitted_to_Sales_Rep__c = IfullfillTextConstant.QUERY_SUBMIT_TO_REP_STATUS;   
        
        // Check if sales rep is overriden and change the owner of the query to overriden salesrep
              
        if(qry.Override_Sales_Rep__c  && qry.Sales_Rep_Name1__c !=null)
        {
             qry.OwnerID = qry.Sales_Rep_Name1__c;    
        }
        else
        {
           if(qry.Sales_Rep_ID__c != null)
             qry.OwnerID = qry.Sales_Rep_ID__c;
        }          
        try
        {
            update qry;
            sendEmail();
            
        }
        catch(dmlexception e){GeneralCOnstants.mailAnyExceptionToMe('ifulfillSubmitToSalesRepController','SubmitToSalesRep',e);}
        String returnUrl = '/'+qry.id;
        Pagereference pgReturnPage = new PageReference(returnUrl);
        pgReturnPage.setRedirect(true); 
        return pgReturnPage;
     
     }  
  
   /*
    *    Action associated with Submit Response button on query page layout. 
    * 
    **/ 
         
    public pagereference SubmitQueryResp()
    {                 
        ID OORQueryId = RecordTypeHelper.GetRecordTypeID('Queries__c', 'OOR Query');           
        qry.Submitted_to_Sales_Rep__c = IfullfillTextConstant.QUERY_RESP_FROM_REP_STATUS;          
        //qry.recordtypeid = OORQueryId;        
        //qry.OwnerID = qry.CreatedById;
        try
        {
            update qry;
        }
        catch(dmlexception e){GeneralCOnstants.mailAnyExceptionToMe('ifulfillSubmitToSalesRepController','SubmitQueryResp',e);}  
        String returnUrl = '/'+qry.id;
        Pagereference pgReturnPage = new PageReference(returnUrl);
        pgReturnPage.setRedirect(true); 
        return pgReturnPage;
    }        
    
    /*
     *  Sends the email to sales rep and manager when user click the submit to sale rep button on query page.
     *
     **/
    public void sendEmail()  
    {       
        List <Profile> profileList  = [select name from profile  where id  = :userinfo.getProfileId()];
        ListViewIds__c listViewIDObj = ListViewIds__c.getInstance(userinfo.getProfileId());
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();  
        String[] toAddresses  =null;
        String[] ccAddresses  = null;
     //   mail.setSenderDisplayName('No Reply');
       // mail.setReplyTo('noreply@attinteractive.com');
       if( listViewIDObj.No_Reply_mail_ID__c !=null)
       {
            mail.setOrgWideEmailAddressId(  listViewIDObj.No_Reply_mail_ID__c);
       }
        
        mail.setSaveAsActivity(false); 
        List <Queries__c>  qryList =[select Query_Request_ID__r.Fulfillment_Item__r.Account__r.name,Query_Request_ID__r.Fulfillment_Item__r.UDAC__C,Query_Request_ID__r.Fulfillment_Item__r.Order_Id_txt__c, Query_Request_ID__r.Fulfillment_Item__r.Sales_Rep__r.name ,    Query_Request_ID__r.Fulfillment_Item__r.Sales_Manager__r.name  ,Query_Request_ID__r.Fulfillment_Item__r.Sales_Manager__r.Manager.FirstName , Query_Request_ID__r.Fulfillment_Item__r.Sales_Manager__r.Manager.LastName from Queries__c where id =:qry.id];
 
        // Email to sent to user of IOG TELE SALES PROFILE.
        if(IfullfillTextConstant.IOG_TELE_SALES_PROFILE_NAME.equalsIgnoreCase(profileList.get(0).name) && qryList.size() > 0)
        {                  
            // Check FI sales rep is override with new sales rep 
            if(qry.Override_Sales_Rep__c)
            {
                toAddresses = qry.Sales_Rep_Email__c !=null ? new String[] {qry.Sales_Rep_Email__c} : null;
                ccAddresses = qry.Sales_Mgr_Email1__c !=null ? new String[] {qry.Sales_Mgr_Email1__c} : null;
            }
            else
            {
                toAddresses = qry.Sales_Rep_Email_Id__c !=null ? new String[] {qry.Sales_Rep_Email_Id__c}: null ;
                ccAddresses = qry.Sales_Mgr_Email__c != null ? new String[] {qry.Sales_Mgr_Email__c}: null ;
            }
               
           //  sales rep email address are populated.
            if(ccAddresses !=null)
                mail.setCcAddresses(ccAddresses);
            if(toAddresses !=null)     
                mail.setToAddresses( toAddresses);            
          String temp ='';  
          
          // Email  mail body text.
          
          String emailBody  ='Fulfillment has discovered some missing or invalid information on the following order or worksheet that must be corrected.  Please login to SalesForce, view the Query Tab, fix query.';
          
          temp = qryList.get(0).Query_Request_ID__r.Fulfillment_Item__r.Order_Id_txt__c == null? '' :qryList.get(0).Query_Request_ID__r.Fulfillment_Item__r.Order_Id_txt__c; 
          emailBody   = emailBody + '\n \n Order ID: ' + temp;
          temp = qryList.get(0).Query_Request_ID__r.Fulfillment_Item__r.UDAC__C== null ? '' :qryList.get(0).Query_Request_ID__r.Fulfillment_Item__r.UDAC__C;
          emailBody   = emailBody + '\n Product ID: ' + temp;
          temp =qryList.get(0).Query_Request_ID__r.Fulfillment_Item__r.Account__r.name ==null ?'' :qryList.get(0).Query_Request_ID__r.Fulfillment_Item__r.Account__r.name;
          emailBody   = emailBody + '\n Business Name: '  + temp;

          // if FI sales rep is override  get the manager details of new salesrep.
          if(qry.Override_Sales_Rep__c)
          {     
              temp ='';    
              emailBody   = emailBody + '\nMedia Consultant:'  + qry.Sales_Rep_Name1__c;
              emailBody   = emailBody + '\nDSM:' +  qry.Sales_Mgr_Name1__c;     
              list<User> salesRegInfo=[Select LastName,FirstName from User where id= :qry.Sales_Mgr_Name1__c];
              if(salesRegInfo.size()>0)
              {
                 temp  =salesRegInfo.get(0).LastName + ' ' + salesRegInfo.get(0).FirstName;
              }
              emailBody   = emailBody + '\nGSM:'+ temp;
          }
          else
          {
              temp = qryList.get(0).Query_Request_ID__r.Fulfillment_Item__r.Sales_Rep__r.name  == null ? '' :qryList.get(0).Query_Request_ID__r.Fulfillment_Item__r.Sales_Rep__r.name;
              emailBody   = emailBody + '\nMedia Consultant:' +temp ;
              temp =   qryList.get(0).Query_Request_ID__r.Fulfillment_Item__r.Sales_Manager__r.name== null?'':qryList.get(0).Query_Request_ID__r.Fulfillment_Item__r.Sales_Manager__r.name;
              emailBody   = emailBody + '\nDSM:'  + temp;
              temp = qryList.get(0).Query_Request_ID__r.Fulfillment_Item__r.Sales_Manager__r.Manager.FirstName== null?'':qryList.get(0).Query_Request_ID__r.Fulfillment_Item__r.Sales_Manager__r.Manager.FirstName;
              temp  = qryList.get(0).Query_Request_ID__r.Fulfillment_Item__r.Sales_Manager__r.Manager.LastName == null ?'' : qryList.get(0).Query_Request_ID__r.Fulfillment_Item__r.Sales_Manager__r.Manager.LastName  + ' '+ temp;
              emailBody   = emailBody + '\nGSM:' + temp;
          }
          
          mail.setPlainTextBody(emailBody );     

          // send the mail only if to or cc address are populated.
          
          if(ccAddresses  != null  ||  toAddresses !=null )
          {
              Messaging.sendEmail(new Messaging.SingleEmailMessage [] { mail });
          }
        }  
    }  
}